package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonStockTaking;
import com.fowo.api.entity.TmpStockTaking;
import com.fowo.api.mapper.AmazonStockTakingMapper;
import com.fowo.api.mapper.TmpStockTakingMapper;
import com.fowo.api.syncAmazon.api.StockTakingReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StockTakingServiceImpl extends ServiceImpl<AmazonStockTakingMapper, AmazonStockTaking> {

    @Resource
    private TmpStockTakingMapper tmpStockTakingMapper;
    @Resource
    private StockTakingReportService stockTakingReportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    @Transactional(rollbackFor = Exception.class)
    public void syncStockTaking() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllStockTaking();
        //拉取数据到临时表
        stockTakingReportService.getStockTaking();
        List<AmazonStockTaking> insertList = new ArrayList<>();
        //获取临时表数据
        List<TmpStockTaking> tmpStockTakings = tmpStockTakingMapper.selectList(new QueryWrapper<>());
        //组装数据
        if (tmpStockTakings != null && tmpStockTakings.size() > 0) {
            for (TmpStockTaking stockTaking : tmpStockTakings) {
                //重复校验
                QueryWrapper<AmazonStockTaking> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("del_flag",0);
                queryWrapper.eq("reference_id",stockTaking.getReferenceId());
                int count = (int)this.count(queryWrapper);
                if(count > 0){
                    continue;
                }
                AmazonStockTaking amazonStockTaking = new AmazonStockTaking();
                BeanUtils.copyProperties(stockTaking, amazonStockTaking);
                amazonStockTaking.setId(null);
                amazonStockTaking.setCreateTime(new Date());
                insertList.add(amazonStockTaking);
            }
            List<List<AmazonStockTaking>> partition = Lists.partition(insertList, 200);
            for (List<AmazonStockTaking> list : partition) {
                this.saveBatch(list);
            }
        }
    }

}
